package offer

import (
	. "GoLeetcode/common"
)

/*
时间复杂度:O(MN)
空间复杂度:O(MN)

dp[i][j] = Min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
*/

func minPathSum(grid [][]int) int {
	m := len(grid)
	n := len(grid[0])
	dp := make([][]int, m)
	for i := range dp {
		dp[i] = make([]int, n)
	}

	dp[0][0] = grid[0][0]
	for i := 1; i < m; i++ {
		dp[i][0] = dp[i-1][0] + grid[i][0]
	}
	for j := 1; j < n; j++ {
		dp[0][j] = dp[0][j-1] + grid[0][j]
	}

	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			dp[i][j] = Min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
		}
	}
	return dp[m-1][n-1]
}


/*
时间复杂度:O(N)
空间复杂度:O(N)

dp[j] = Min(dp[j], dp[j-1]) + grid[i][j]
*/

func minPathSum1(grid [][]int) int {
	m := len(grid)
	n := len(grid[0])
	dp := make([]int, n)
	dp[0] = grid[0][0]
	for i := 1; i <n; i++ {
		dp[i] = dp[i-1] + grid[0][i]
	}

	for i := 1; i < m; i++ {
		dp[0] += grid[i][0]
		for j := 1; j < n; j++ {
			dp[j] = Min(dp[j], dp[j-1]) + grid[i][j]
		}
	}
	return dp[n-1]
}